﻿using System;
using System.Collections.Generic;
using System.Text;

using YouHP.Model;
using YouHP.IDAL;
using Microsoft.ApplicationBlocks.Data;
using System.Data;

namespace YouHP.SqlServerDAL
{
    public class DistrictDAL : IDistrict
    {

        #region 地区

        public bool AddDistrict(DistrictInfo info)
        {
            int cnt = SqlHelper.ExecuteNonQuery(Common.ConnStr,
                Common.DistrictSP_AddDistrict,
                info.Name, info.ParentId, info.OrderValue);
            return cnt > 0;
        }

        public bool DelDistrict(int[] itemIds)
        {
            if (itemIds.Length == 0) return false;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(" [id] in ({0}", itemIds[0]);
            int cnt = itemIds.Length;
            for (int i = 1; i < cnt; i++)
            {
                sb.AppendFormat(",{0}", itemIds[i]);
            }
            sb.Append(") ");
            int cnt2 = SqlHelper.ExecuteNonQuery(Common.ConnStr,
                Common.DistrictSP_DelDistrict,
                sb.ToString());
            return cnt2 >= cnt;
        }

        public bool UpdateDistrict(DistrictInfo info)
        {
            int cnt = SqlHelper.ExecuteNonQuery(Common.ConnStr,
                Common.DistrictSP_UpdateDistrict,
                info.Id, info.Name, info.ParentId, info.OrderValue);
            return cnt > 0;
        }

        public DistrictInfo GetDistrict(int id)
        {
            IDataReader reader = SqlHelper.ExecuteReader(Common.ConnStr,
                Common.DistrictSP_GetDistrict,
                id);
            return CBO.FillObject<DistrictInfo>(reader);
        }

        public List<DistrictInfo> GetDistrictListByParent(int parentId)
        {
            string condstr = string.Format(" [parentid]={0} ", parentId);
            return GetDistrictList(condstr);
        }

        public List<DistrictInfo> GetDistrictList()
        {
            return GetDistrictList("");
        }

        private List<DistrictInfo> GetDistrictList(string condstr)
        {
            IDataReader reader = SqlHelper.ExecuteReader(Common.ConnStr,
                Common.DistrictSP_GetDistrictList,
                condstr);
            return CBO.FillCollection<DistrictInfo>(reader);
        }

        #endregion
    }
}
